package com.mingyuan;

import com.mingyuan.demo1.ByteBuddyAgentTransformer;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.dynamic.scaffold.TypeValidation;

import java.lang.instrument.Instrumentation;

import static net.bytebuddy.matcher.ElementMatchers.nameStartsWith;

public class PremainAgent {


    public final static String scanPackage = "com.mingyuan.showCode";
    public final static String sayHelloMethod = "sayHello";

    public final static String nacosStartMethod = "nacosStart";

    /**
     * JVM 首先尝试在代理类上调用以下方法
     * 该方法在main方法之前运行，
     * 与main方法运行在同一个JVM中
     */
    public static void premain(String agentArgs, Instrumentation inst) {
        System.out.println("=========premain方法执行 1 JVM 首先尝试在代理类上调用========");
        //inst.addTransformer(new HelloTransformer());
        final ByteBuddy byteBuddy = new ByteBuddy().with(TypeValidation.of(false));
        new AgentBuilder.Default(byteBuddy)
                .type(nameStartsWith(scanPackage))
                .transform(new ByteBuddyAgentTransformer()) // update the byte code
                .installOn(inst);
    }

    /**
     * 候选的、兜底 方法：
     * 如果不存在 premain(String agentArgs, Instrumentation inst)
     * 则会执行 premain(String agentArgs)
     *
     */
    public static void premain(String agentArgs) {
        System.out.println("=========premain 方法执行 2 候选的、兜底 ========");
        System.out.println("agentArgs:="+agentArgs);
    }


}

